package qjc.g_链表;

import com.链表.练习题.ListNode;

public class g3_回文链表 {
    /**
     * 找到链表的中点，反转链表的后半部分，比较前半部分和反转后的后半部分
     */
    public boolean isPalindrome(ListNode head) {
        ListNode middle = findMiddle(head);
        ListNode reverse = reverseList(middle);
        while (reverse != null){
            if(reverse.val != head.val){
                return false;
            }
            reverse = reverse.next;
            head = head.next;
        }
        return true;
    }

    private ListNode reverseList(ListNode head) {
        ListNode n1 = null;
        while (head != null){
            ListNode n2 = head.next;
            head.next = n1;
            n1 = head;
            head = n2;
        }
        return n1;
    }

    private ListNode findMiddle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

}
